package com.lge.clock.alarmclock;
 
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import android.app.Fragment;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemProperties;
import android.os.Vibrator;
//import android.os.SystemProperties;
import android.provider.MediaStore;
import android.provider.Settings;
import android.os.Environment; // [suhyun99.kim][1395] 2011.10.27.
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.widget.Toast;

import com.lge.clock.AlarmClockActivity;
import com.lge.clock.AlarmFragment;
import com.lge.clock.R;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.CommonUtil.OPERATOR;
import com.lge.clock.util.Log;
import com.lge.clock.worldclock.cities.CityDBManager;

/**
 * @author LGE Cappuccino
 */
public class ALReceiver extends BroadcastReceiver implements AlarmConstants {
	private static final String TAG = "AlarmReceiver";
	private static final String PREFERENCES = "com.lge.clock_preferences";
	
	// fred.lee@lge.com -XenerSystems 
	/**
	 * Field EXTRA_STATE_IDLE.
	 * (value is 0)
	 */
	public static final int EXTRA_STATE_IDLE = 0;		// waiting
	/**
	 * Field EXTRA_STATE_OFFHOOK.
	 * (value is 2)
	 */
	public static final int EXTRA_STATE_OFFHOOK = 2;	// calling
	/**
	 * Field EXTRA_STATE_RINGING.
	 * (value is 1)
	 */
	public static final int EXTRA_STATE_RINGING = 1;	// ringing
	/**
	 * Field EXTRA_STATE_OUTGOING.
	 * (value is 3)
	 */
	public static final int EXTRA_STATE_OUTGOING = 3;   // outgoing
	private final String state = "state";
	private static int voip_callState = EXTRA_STATE_IDLE;
    private static final String VOIP_CALL_STATE = "android.intent.action.VOIP_CALL_STATE";
	private static final String FORCESTOP = "com.android.am.action.FORCESTOP";
	private static final String CLEAR_DATA = "com.android.settings.CLEAR_DATA";
	public static final String DELETE_WIDGET_URI = "com.lge.worldclock.deletecity";
	private static final String CLOPACKAGE="com.lge.clock";
	private static final String SHUTDOWN = "android.intent.action.ACTION_SHUTDOWN";
	//......
	private TelephonyManager mTelephonyManager;
	
	private Vibrator vibrator;
	
	private String temp_TONE    = "";
    private String temp_VIB     = ""; 
    private String temp_MEMO    = ""; 
    private String temp_PUZZLE  = "";
	
/* I3.0 Code [START] */
    private String temp_ALARMVOLUME = "";
/* I3.0 Code [END] */
    /** If the alarm is older than STALE_WINDOW seconds, ignore.  It
    is probably the result of a time or timezone change */
    private static final int STALE_WINDOW = 60 * 30;
    private static final int STOPSIGN = 1008;
    //................................................................

    // [suhyun99.kim][1395] 2011.10.27. START
    private static final String MEDIA_MOUNTED = "android.intent.action.MEDIA_MOUNTED";
    private final String[] PROJECTION = {
		"_id",
    		"tone"
    };
    // [suhyun99.kim][1395] 2011.10.27. END
    
    /** Indicate if phone is in emergency callback mode */
    private static final String PROPERTY_INECM_MODE = "ril.cdma.inecmmode";
	
    /**
     * Method onReceive.
     * @param context Context
     * @param intent Intent
     */
    @Override
	public void onReceive(Context context, Intent intent) {
		Log.d(TAG, "==[[ ALReceiver intent ]]===> " + intent.getAction() );
		ContentResolver resolver = context.getContentResolver(); 
		NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		mTelephonyManager =	(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		
		// Power-Off : alarm killed
//		String strRequestShutDown = Intent.ACTION_REQUEST_SHUTDOWN;
//        if ( strRequestShutDown.equalsIgnoreCase(intent.getAction()) ||  
		if (Intent.ACTION_SHUTDOWN.equalsIgnoreCase(intent.getAction())) 
        {
        	SharedPreferences mPrefs = context.getSharedPreferences("ALARM_BOOT_COMPLETED", 0);
        	mPrefs.edit().putBoolean ("BOOT_COMPLETED", false).commit();
        	AlarmClockActivity.mShutDown = true;
        	killOnProcess(context);
        	return; 
        }
        if ( FORCESTOP.equalsIgnoreCase(intent.getAction()))
        {
        	Alarms.setStatusBarIcon(context, false);
        	killOnProcess(context);
        	return; 
        }
        
        if(CLEAR_DATA.equalsIgnoreCase(intent.getAction())){
			Alarms.setStatusBarIcon(context, false);
			Alarms.disableAlert(context, 0);//P930_TD#17729_20110728 put system setting for lock screen merge victor by hyunjung78.park
			Intent sendIntent = new Intent(DELETE_WIDGET_URI);
			sendIntent.putExtra("deleteAll", true);//P930_20110728 modify wrong intent name by hyunjung78.park
			context.sendBroadcast(sendIntent);
			killOnProcess(context);
		}
        /*[START] 2012.02.03 suein1209.kim*/
		// [suhyun99.kim][1395] 2011.10.27. START
//        String sd_state = intent.getAction(); 
//        if (MEDIA_MOUNTED.equalsIgnoreCase(sd_state)) {
//			sdChangeProc(context);
//			return;
//        }
		// [suhyun99.kim][1395] 2011.10.27. END
        /*[END] 2012.02.03 suein1209.kim*/
        
        if (VOIP_CALL_STATE.equalsIgnoreCase(intent.getAction())) {
        	Log.d(TAG, "VOIP Phone receive action type ");
        	
        	voip_callState = intent.getIntExtra(state, EXTRA_STATE_IDLE);
        	Log.d(TAG, "state : " + voip_callState);
        	///////////////////////////////////////////////////////////////
        	//Voip outgoing 3 -> 2-> 0  in order intent
        	//Voip incomming 1 -> 2 -> 0  in order intent 
        	SharedPreferences prefs = context.getSharedPreferences(PREFERENCES, 0);
        	if (voip_callState != 0) {
        		if (alarmRingingAlert(context) == true) {
        			return;
        			
        		}else {
        			// current Voip calling VISIBLE
                	prefs.edit().putString("voip_state", "1").commit(); 
        		}
        	}else {
        		// Voip calling stop
        		prefs.edit().putString("voip_state", "0").commit(); 
        	}         	
        	return; 
        } 
        
        // get id
        int id = intent.getIntExtra("id", 0);
        if (Alarms.ALARM_STOP.equals(intent.getAction())) {
    		Log.d(TAG, "===08/26===ALARM_STOP ID==================>" + id);
            nm.cancel(id);
    		return;
        } 
		/** If the alarm is older than STALE_WINDOW seconds, ignore.  
         * It  is probably the result of a time or timezone change */
        /*
        long now = System.currentTimeMillis();
        if (now > RTime + STALE_WINDOW * 1000) {
            Log.d(TAG, "ALReceiver ignoring stale alarm intent id" + id + " setFor " + RTime + " now " + now);
            return;
        }
		*/
        
        if (Alarms.CANCEL_SNOOZE.equalsIgnoreCase(intent.getAction())) {
        	Log.d(TAG, "== CANCEL_SNOOZE ID ===>" + id) ;
            nm.cancel(id);             
	        resolver.delete(ALProvider.CONTENT_CALCU_URI, "aid = " + id + " and aindex > 0",  null);
	                                                  
	        /** 
	        *    in case not repeat 
	         */
	        Alarms.noRepeatChecking(context, id, false);
	                                
	        /**
	         *   next alarm
	         */
	        Alarms.setNextAlert(context);      
	        // Below comments are temporal, because Activitys change to Fragments. [sangkyeong.jeong@lge.com]
//	        Fragment alarmActivityContext = AlarmFragment.
//	        if ( alarmActivityContext != null )
//	        	((AlarmFragment)alarmActivityContext).onResumeFunc();
	        return;
        }
        
        /////////// when Camera & Voice Recoring, alarm stop///////////////
        boolean voice_video_playing_YN = false ;
        SharedPreferences prefs = context.getSharedPreferences("VOICE_VIDEO_RECORD_PLAYING", 0);
        SharedPreferences.Editor ed = prefs.edit();
        int play_stateYN = prefs.getInt("PLAY_STATE", 0);
        if (play_stateYN == 1) {
        	voice_video_playing_YN = true;
        }
               
        /**
         *       recording start action obtain
         */
        if ("voice_video_record_playing".equalsIgnoreCase(intent.getAction())) 
        {
        	ed.putInt("PLAY_STATE", 1);
        	ed.commit();            
        	  
        	Log.d(TAG, "=========[ voice_video_record_playing ]=======" + prefs.getInt("PLAY_STATE", 0));
        	Log.e(TAG, Boolean.toString(voice_video_playing_YN) + "   recording start!!");
        	voice_video_playing_YN = true ;
        	return;
        	
    	}
         
          
        /**
         *       recording stop action obtain
         */  
        if ("voice_video_record_finish".equalsIgnoreCase(intent.getAction())) 
        {
        	if (play_stateYN == 0) {
        		return;  
        	}   
			ed.putInt("PLAY_STATE", 0);
        	ed.commit();
        	voice_video_playing_YN = false ;
        	Log.e(TAG, Boolean.toString(voice_video_playing_YN) + "   recording end!!");
        	
        	//WakeAlarms(context); //not delay alarm!  
        	return;
        }
        
        /** If the alarm is older than STALE_WINDOW seconds, ignore.  
         * It  is probably the result of a time or timezone change */
        long rTime = intent.getLongExtra("time", 0);  
        long now = System.currentTimeMillis();
        if (now > rTime + STALE_WINDOW * 1000) {
            Log.d(TAG, "ALReceiver ignoring stale alarm intent id" + id + " setFor " + rTime + " now " + now);
            return;
        }
        //////////////////////////////////////////////////////////////////////
        String  memo  = intent.getStringExtra("memo"); 
        String  gubun  = intent.getStringExtra("gubun"); 
        String	tone  = intent.getStringExtra("tone");
        String	vib   = intent.getStringExtra("vib");    
        String	puzzle   = intent.getStringExtra("puzzle");
        //String  stopflag  = intent.getStringExtra("stop");
        int	snooze    = intent.getIntExtra("snooze", 5);
        
        
/* I3.0 Code [START] */
		boolean isUseVolumeControl = CommonUtil.isUseVolumeControl();
		String alarmVolume = null;
		if( isUseVolumeControl )
			alarmVolume = intent.getStringExtra(AlarmMeta.COLUMNS.ALARM_VOLUME);
/* I3.0 Code [END] */
		
        //////////////////////////////////////////////////////////////////////
        Intent fireAlarm = new Intent(context, AlarmAlert.class); 
        fireAlarm.putExtra("id", id);
        fireAlarm.putExtra("memo", memo);      
                                           
        fireAlarm.putExtra("puzzle", puzzle);
        fireAlarm.putExtra("time", 	 rTime); 
        fireAlarm.putExtra("snooze", snooze); 
        fireAlarm.putExtra("tone", tone); 
        fireAlarm.putExtra("vib", vib);              
        fireAlarm.putExtra("stop", intent.getStringExtra("stop") ); 
        fireAlarm.putExtra("gubun",  gubun);    
        fireAlarm.putExtra("multi", intent.getStringExtra("multi") );     
/* I3.0 Code [START] */
        if(isUseVolumeControl){
			fireAlarm.putExtra(AlarmMeta.COLUMNS.ALARM_VOLUME, alarmVolume);
        }
/* I3.0 Code [END] */
        fireAlarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); 
                              
        /**
         *   when current is recording, alarm/snooze treatment start
         */     
        if (voice_video_playing_YN == true){
                	
        	Log.e(TAG, Boolean.toString(voice_video_playing_YN));

        	if (0 == snooze)
        	{
        	if ( "snooze".equalsIgnoreCase(gubun)) {
        		int  pk   	   =	intent.getIntExtra("pk", 0);
        		resolver.delete(ALProvider.CONTENT_CALCU_URI, "_id = " + pk,  null);
        		autoSnoozeGoAhead(context, id, memo, snooze, tone, vib, puzzle);
                    	
        		CharSequence message = context.getText(R.string.alarm).toString() + " " +  getCalendar(rTime, context)
        		    								+ context.getText(R.string.user_pause).toString();
        		Toast.makeText(context, message,  Toast.LENGTH_LONG).show();   
        	} 
        	else if ( "alarm".equalsIgnoreCase(gubun)){
        		autoStop(context, id, memo, rTime);
        	}  
        }
        else {
    		snoozeSetting(context, intent, resolver, id, memo, snooze, tone, vib, puzzle, rTime);
        }
                	 
			/**
			 * alarm/snooze/duplicate check => save
	             */
        	multiCheck(context, id, rTime);  
            Alarms.setNextAlert(context);  
            		
            return;
        }
        	
       /*[START] 2012.04.04 suein1209.kim*/
//        if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
        /*[END] 2012.04.04 suein1209.kim*/
        if (CommonUtil.isCallStateIdle(mTelephonyManager, context) == false) {
	        // [minjoong.park][1398] 2011.10.15. START
//        	boolean isVzw = CommonUtil.isVZW();
//        	Log.e(TAG, "isVzw => " + isVzw);
//        	if(isVzw){
        	
        	if(CommonUtil.getBuildOperator() == OPERATOR.VZW){
        		
        		if(isEmergencyCallMode()){
        			/*emergency calling*/
        			
            		/*do vib action*/
            		doVibratorAction(context);

            		/*do auto snooze*/
                	doCommonAutoSnooze(context, intent, resolver, id, rTime, memo, tone, vib, puzzle, snooze);
                	
        		}else{
        			/*nomal calling*/
        			/*[START] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
//        			AlarmAlertWakeLock.acquireCpuWakeLock(context);
        			/*[END] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
        			
        			/*do vib action*/
        			doVibratorAction(context);
        			
        			/*start alarm dialog*/
/* [I3.0] Code START */
        			startAlarmDialog(context, intent, id, rTime, memo, gubun, tone, vib, puzzle, snooze, alarmVolume);
/* [I3.0] Code END */
        		} //End Of if
        		
        	}else{
        		/*do vib action*/
        		doVibratorAction(context);

        		/*do auto snooze*/
            	doCommonAutoSnooze(context, intent, resolver, id, rTime, memo, tone, vib, puzzle, snooze);
        	}
   	        // [minjoong.park][1398] 2011.10.15. END
            
            return;
        }
        
        /*[START] 2012.03.05 suein1209.kim VT Call State issue*/
        SharedPreferences mVtCallPrefs = context.getSharedPreferences("VT_CALL_IN_OR_OUT_STATE", 0);
        
//        final String mHDVTStatus = "2";//SystemProperties.get("net.ims.vt.incall");
//        if (mHDVTStatus != null && "1".equals(mHDVTStatus)) 
        if (mVtCallPrefs.getBoolean("VTCALL_IN_STATE", false)){
        	Log.d(TAG, "========= HDVT Call is incall status =======");
//    		if (0 == snooze) {
//    			snooze = 5;
//    		}
        	
    		/*do vib action*/
    		doVibratorAction(context);

//            snoozeSetting(context, intent, resolver, id, memo, snooze, tone, vib, puzzle, rTime);
            
            /*do auto snooze*/
        	doCommonAutoSnooze(context, intent, resolver, id, rTime, memo, tone, vib, puzzle, snooze);
            
            /**
        	 * alarm/snooze/duplicate check => save
             */		
//            multiCheck(context, id, rTime);  
//            Alarms.setNextAlert(context);
            return;
        } 
        /*[END] 2012.03.05 suein1209.kim VT Call State issue*/
                
        /**
         *    not recording       
         */
        if ("alarm".equalsIgnoreCase(gubun)) {
        	Log.e(TAG, Boolean.toString(voice_video_playing_YN));
        	// MediaPlayer mp = new MediaPlayer();
        	
        	AlarmAlertWakeLock.acquireCpuWakeLock(context);
	        AlarmAlertWakeLock.acquireScreenWakeLock(context);
	        // The details of our fake message
	    	CharSequence from = context.getText(R.string.alarm).toString(); // // + "(" + memo + ")";
	        //if (memo == null || "".equals(memo.trim())) {
	        //	from =  context.getText(R.string.alarm).toString();  
	        //}
	                        
	        CharSequence message = context.getText(R.string.user_select).toString();
	        //[mo2sangbong.lee][1596] 2011.10.26 START
	        PendingIntent contentIntent = PendingIntent.getActivity(context, id, fireAlarm, 0);
	        //[mo2sangbong.lee][1596] 2011.10.26 END
	        Notification notif = new Notification(R.drawable.stat_notify_alarm, from, rTime );
	      
	        // Set the info for the views that show in the notification panel.
	        notif.setLatestEventInfo(context, from, message, contentIntent);
	        notif.flags |= Notification.FLAG_ONGOING_EVENT;
	        
	        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
	        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
	        		&& CommonUtil.isPowerLEDSetInSettings(context.getContentResolver()) == 0){
	        	
	        	notif.flags |= Notification.DEFAULT_LIGHTS;
	        	
	        }else{
	        	
	        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
	        	notif.defaults |= Notification.DEFAULT_LIGHTS;
	        	
	        } //End Of if
//	        notif.ledARGB = 0xFF00FF00;
//	        notif.ledOnMS = 500;
//	        notif.ledOffMS = 500;
	        nm.notify(id,  notif);                
			context.startActivity(fireAlarm); 
			return;
        }
         
        if ("snooze".equalsIgnoreCase(gubun)) {
        	int  pk   	   =	intent.getIntExtra("pk", 0);
        	resolver.delete(ALProvider.CONTENT_CALCU_URI, "_id = " + pk,  null);
        	      
        	AlarmAlertWakeLock.acquireCpuWakeLock(context);
	        AlarmAlertWakeLock.acquireScreenWakeLock(context);
	        // The details of our fake message
	        CharSequence from = memo;
	    	if (memo == null || "".equals(memo.trim())) {
	        	from = context.getText(R.string.alarm).toString(); 
	        }
	          
	    	CharSequence message = context.getText(R.string.user_select).toString();
	    	//[mo2sangbong.lee][1596] 2011.10.26 START
	        PendingIntent contentIntent = PendingIntent.getActivity(context, id, fireAlarm, 0);
	        //[mo2sangbong.lee][1596] 2011.10.26 END
	        Notification notif = new Notification(R.drawable.stat_notify_alarm, from, rTime );
	      
	        // Set the info for the views that show in the notification panel.
	        notif.setLatestEventInfo(context, from, message, contentIntent);
	        notif.flags |= Notification.FLAG_ONGOING_EVENT;
	        notif.flags |= Notification.DEFAULT_LIGHTS;
	        
	        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
	        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
	        		&& CommonUtil.isPowerLEDSetInSettings(context.getContentResolver()) == 0){
	        	
	        	/*Do nothing*/
	        	
	        }else{
	        	
	        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
	        	
	        } //End Of if
//	        notif.ledARGB = 0xFF00FF00;
//	        notif.ledOnMS = 500;
//	        notif.ledOffMS = 500;
	        nm.notify(id,  notif);
        	context.startActivity(fireAlarm);
        	return;
        }//.....
	}

    /**
     * suein1209.kim
     * 
     * do common auto snooze
     * @param context
     * @param intent
     * @param resolver
     * @param id
     * @param rTime
     * @param memo
     * @param tone
     * @param vib
     * @param puzzle
     * @param snooze
     */
	private void doCommonAutoSnooze(Context context, Intent intent,
			ContentResolver resolver, int id, long rTime, String memo,
			String tone, String vib, String puzzle, int snooze) {
		
		if (0 == snooze) {
			//TD#89568 : Fixed not to auto-snooze if snooze duration is off.
//			snooze = 5;
			autoStop(context, id, memo, rTime);			
		}
		else {
			snoozeSetting(context, intent, resolver, id, memo, snooze, tone, vib, puzzle, rTime);
		}
		
		/**
		 * alarm/snooze/duplicate check => save
		 */		
		multiCheck(context, id, rTime);  
		Alarms.setNextAlert(context);
		
	} //End of Method doCommonAutoSnooze

    /**
     * suein1209.kim
     * vib action when calling
     * @param context
     */
	private void doVibratorAction(Context context) {
		
		vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
		
		if(CommonUtil.getBuildOperator() == OPERATOR.VZW){
			vibrator.vibrate(new long[] { 130, 220, 130, 200 }, 0);
		}else{
			vibrator.vibrate(new long[] { 130, 220 }, 0);
		} //End Of if
		
		mVibHandler.sendMessageDelayed(mVibHandler.obtainMessage(STOPSIGN), 800);
	} //End Of Method doVibratorActionWithCalling
    
    /**
     * suein1209.kim
     * start Alarm Dialog
     */
	private void startAlarmDialog(Context context, Intent intent, int id,
			long rTime, String memo, String gubun, String tone, String vib,

/* [I3.0] Code START */
			String puzzle, int snooze, String alarmVolume) {
/* [I3.0] Code END */
		
		Intent mIntent = new Intent(context, AlarmDialog.class);
		mIntent.putExtra("id", id);
		mIntent.putExtra("snooze", snooze);
		mIntent.putExtra("memo", memo);
		mIntent.putExtra("puzzle", puzzle);
		mIntent.putExtra("tone", tone);
		mIntent.putExtra("vib", vib);
		mIntent.putExtra("time", 	 rTime);
		mIntent.putExtra("stop", intent.getStringExtra("stop") );
		mIntent.putExtra("gubun",  gubun);
		
/* [I3.0] Code START */
		if(alarmVolume != null);
			mIntent.putExtra(AlarmMeta.COLUMNS.ALARM_VOLUME, alarmVolume);
/* [I3.0] Code END */
		
		mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		context.startActivity(mIntent);
	} //End Of Method startAlarmDialog
    
    /**
     * suein1209.kim
     * check emergency call mode
     */
    private boolean isEmergencyCallMode(){
        // [START]Alarm auto snooze status on emergency callback mode
        boolean ecm_state = false;
        try{
        	ecm_state = (Boolean.parseBoolean(SystemProperties.get(PROPERTY_INECM_MODE)));
        }catch(Exception e){
        	
        	Log.e(TAG, "Exception -> ALReceiver -> isEmergencyCallMode : "+e.getMessage());
        }
        
        android.util.Log.d(TAG, "Emergency Call : "+ecm_state);
        
        // [END]Alarm auto snooze status on emergency callback mode
        
    	return ecm_state;
    } //End Of Method isEmergencyCallMode
    
        
    private final Handler mVibHandler = new Handler() {
	    public void handleMessage(Message msg) {
	    	switch (msg.what) 
	    	{
	    		case STOPSIGN :
	    			if (vibrator != null)
	    				vibrator.cancel();
	    			break;
	    			
	    		default :
	    			break;
	    	}
	    }
	};
	
    private void snoozeSetting(Context context, Intent intent, ContentResolver resolver, int id, String  memo
    		, int snooze, String tone, String vib, String puzzle, long rTime) {
    	int  pk   	   =	intent.getIntExtra("pk", 0);
    	resolver.delete(ALProvider.CONTENT_CALCU_URI, "_id = " + pk,  null);
    	autoSnoozeGoAhead(context, id, memo, snooze, tone, vib, puzzle);
 
        CharSequence from =  context.getText(R.string.sp_snooze_ment_NORMAL).toString() + "(" + memo + ")";
        if (memo == null || "".equals(memo.trim())) {
           	from =  context.getText(R.string.sp_snooze_ment_NORMAL).toString();  
        }

        CharSequence[] snooze_button_popup = context.getResources().getTextArray(R.array.sp_snooze_popup_NORMAL);
        int[] timeMap = {5,10,15,20,25,30,60};
        String showMessage = "";
        for (int i = 0; i < timeMap.length; i++) {
        	if (timeMap[i] == snooze) {
        		showMessage = (String)snooze_button_popup[i];
        		break;
        	}
        }
        CharSequence message = context.getText(R.string.alarm_ment1).toString() + " " +  getCalendarNow(rTime, context, snooze);
            
        NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notiManager.cancel(id);
        Toast.makeText(context, showMessage, Toast.LENGTH_LONG).show();
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        Notification notif = new Notification(R.drawable.stat_notify_alarm, from, 0 );
        // Set the info for the views that show in the notification panel.
        Intent cancelSnooze = new Intent(context, ALReceiver.class);
        cancelSnooze.setAction(Alarms.CANCEL_SNOOZE);
        cancelSnooze.putExtra("id", id);
            
        PendingIntent broadcast =	PendingIntent.getBroadcast(context, id, cancelSnooze, 0);
        notif.setLatestEventInfo(context, from, message, broadcast);
        notif.deleteIntent = broadcast;
        notif.defaults |= Notification.DEFAULT_LIGHTS;
        
        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
        		&& CommonUtil.isPowerLEDSetInSettings(context.getContentResolver()) == 0){
        	
        	notif.flags |= Notification.DEFAULT_LIGHTS;
        	
        }else{
        	
        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
        	notif.defaults |= Notification.DEFAULT_LIGHTS;
        	
        } //End Of if
//        notif.ledARGB = 0xFF00FF00;
//        notif.ledOnMS = 500;
//        notif.ledOffMS = 500;
        notiManager.notify(id,  notif);
        ///////////// end /////////////////////////////////////
    }
	/**
	 * donggeun.kim
	 * case2) during alarm, when alarm delete, alarm activity kill
	 * @param _id
	 */
	private void killOnProcess2(String strID) {
	   	Log.d(TAG, "===Delete====_id===>" + strID);
	               	
	   	AlarmAlert aa = (AlarmAlert)AlarmAlert.mAlarmSavings.get(strID);
		if (aa == null) {
	   		return;
	   	}
	   	aa.forceStop();
	   	AlarmAlert.mAlarmSavings.remove(strID);
	}
	
	/**
	 * donggeun.kim
	 * case1) during alarm, when power off click, alarm activity kill
	 * @param _id
	 */
	private void killOnProcess(Context context) {
		Map.Entry<String, AlarmAlert>temp;
        Set ee ;
        Iterator ii ;
        ee = AlarmAlert.mAlarmSavings.entrySet();
        ii =  ee.iterator();
         
        //boolean check = false; 
        // key value & response value of all entry output
        while( ii.hasNext()) {
            temp = (Map.Entry<String, AlarmAlert>) ii.next();
            String strID = (String)temp.getKey();
            
        	Log.d(TAG, "===Delete====_id===>" + strID);    
        	NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        	
        	try {
        		nm.cancel( Integer.parseInt(strID) );
        	} catch ( NumberFormatException e ) {
        		e.printStackTrace();
        	}
                    	
        	AlarmAlert aa = (AlarmAlert)AlarmAlert.mAlarmSavings.get(strID);
        	// 20101012_mhkwon_WBT166511_Null pointer dereference of 'aa' where null is returned from a map or a collection [[
        	if (aa == null ){
        	    continue; 
        	}  
        	// 20101012_mhkwon_WBT166511_Null pointer dereference of 'aa' where null is returned from a map or a collection ]]
        	aa.forceStop();
        }    
	}
	 
	private boolean alarmRingingAlert(Context context) {
		boolean returnTag = false;
		Map.Entry<String, AlarmAlert>temp;
        Set ee ;
        Iterator ii ;
        ee = AlarmAlert.mAlarmSavings.entrySet();
        ii =  ee.iterator();
         
        //boolean check = false; 
        // key value & response value of all entry output
        while( ii.hasNext() ) {
            temp = (Map.Entry<String, AlarmAlert>) ii.next();
            String strID = (String)temp.getKey();
            
        	Log.d(TAG, "===Delete====_id===>" + strID); 
        	NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        	try {
        		nm.cancel( Integer.parseInt(strID) );
        	} catch ( NumberFormatException e ) {
        		e.printStackTrace();
        	}
            
        	AlarmAlert aa = (AlarmAlert)AlarmAlert.mAlarmSavings.get(strID);
        	// 20101012_mhkwon_WBT166511_Null pointer dereference of 'aa' where null is returned from a map or a collection [[
        	if (aa == null ){
        	    continue;
        	}  
        	// 20101012_mhkwon_WBT166511_Null pointer dereference of 'aa' where null is returned from a map or a collection ]]
        	
        	aa.forceStop_Related_voip();
        	returnTag = true;
        }
         
        return returnTag;
	}

	private static boolean get24HourMode(final Context context) {
        return android.text.format.DateFormat.is24HourFormat(context);
    }
	private boolean getDateFormat(Context context) {
    	if (get24HourMode(context) == true) {
    		m1Format = M24_CHECK;
    		return true;
    	}    	
    	m1Format = M12_CHECK;
    	return false;
    }
	
	private String m1Format;
    /**
     * Field M24_CHECK.
     * (value is ""kk:mm"")
     */
    static final String M24_CHECK = "kk:mm";   
	/**
	 * Field M12_CHECK.
	 * (value is ""h:mm"")
	 */
	static final String M12_CHECK = "h:mm";
	/**
	 * Method getCalendar.
	 * @param time long
	 * @param context Context
	 * @return String
	 */
	public String getCalendar(long time, Context context) {
		Calendar aa = Calendar.getInstance( );  // current date/time etc.. obtain info
		aa.setTimeInMillis(time);
       
		// is24HourFormat
    	if (true == getDateFormat(context)) {
    		CharSequence alarmtime = DateFormat.format(m1Format, aa);
	    	return (alarmtime.toString());
    	}
	    // is12HourFormat
    	else {
    		CharSequence alarmtime = DateFormat.format(m1Format, aa);
	        boolean bAPM = aa.get(Calendar.AM_PM) == 0;
	        
	        if ( bAPM == true ) {
	        	return (alarmtime.toString() + " " + context.getText(R.string.sp_AM_string_NORMAL).toString());
	        } else {
	        	return (alarmtime.toString() + " " + context.getText(R.string.sp_PM_string_NORMAL).toString());
	        }
    	}
	}
			
	private String getCalendarNow(long time , Context context, int snooze) {
		time = time + (1000 * 60 * snooze);
    	Calendar aa = Calendar.getInstance( );
    	aa.setTimeInMillis( time );

    	// is24HourFormat
    	if ( getDateFormat(context) ) {
    		CharSequence alarmtime = DateFormat.format(m1Format, aa);
	    	return (alarmtime.toString() + ". " + context.getText(R.string.sp_alarm_right_ment_NORMAL).toString());
    	}
	    // is12HourFormat
    	else {
    		CharSequence alarmtime = DateFormat.format(m1Format, aa);
	        boolean bAPM = aa.get(Calendar.AM_PM) == 0;
	        if ( bAPM ) {
	        	return (alarmtime.toString() + " " + context.getText(R.string.sp_AM_string_NORMAL).toString()
	        			+ "." + " " + context.getText(R.string.sp_alarm_right_ment_NORMAL).toString());
	        } else {
	        	return (alarmtime.toString() + " " + context.getText(R.string.sp_PM_string_NORMAL).toString()
	        			+ "." + " " + context.getText(R.string.sp_alarm_right_ment_NORMAL).toString());
	        }
    	}
    }
	 
	/**
     *   multialarm, multisnooze  check => save 
     */     
    private void multiCheck(Context context, int mId, long mTime) {
    	final String[] calcuCols = { "_id",  "aid",  "time", "aindex", "status", "stop" };
    	ContentResolver resolver = context.getContentResolver();
    	Cursor cc = null;
		try {
			cc = resolver.query(Uri.parse(("content://com.lge.clock.alarmclock.ALProvider/calcus").concat("?calcuqueryType=1")), calcuCols, 
					 "enabled = '1' and time = " + mTime + "  and  aid != " + mId, null, "time, status, aid"  );
			Log.d(TAG, "====multiCheck==== / Id : " + mId + " time : " + mTime) ;
			if ( cc != null && cc.moveToFirst() ) {//[hyunjung78.park] 2011.08.09 cursor null check
				do { 
					int snooze = 0;
					//int pk   =	cc.getInt(0);       
					int aid  =	cc.getInt(1);
					int aindex = cc.getInt(3);
					
					Log.d(TAG, " multiCheck - alarm Next ID - " + aid + "  ========================> " + aindex);
					
					if (aindex == 0) {
						Intent intent = new Intent(context, ALReceiver.class); 
						intent.setAction(Alarms.ALARM_STOP);
						intent.putExtra("id", 	   aid );
						intent.putExtra("time",   mTime);     
						
						intent.putExtra("gubun",  "alarm");
						snooze = getSnoozeTime(context, aid);
						intent.putExtra("snooze",  snooze); 
						if (snooze > 0) {
							intent.putExtra("stop",  "");
						} else {
							intent.putExtra("stop",  "stop");
						}
						intent.putExtra("memo",   temp_MEMO);
						intent.putExtra("puzzle", temp_PUZZLE);
						intent.putExtra("tone",   temp_TONE);
						intent.putExtra("vib",    temp_VIB); 
/* I3.0 Code [START] */
						if(CommonUtil.isUseVolumeControl()){
							intent.putExtra(AlarmMeta.COLUMNS.ALARM_VOLUME, temp_ALARMVOLUME);
						}
/* I3.0 Code [END] */
						intent.putExtra("multi",  "yes");  
						
						NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
						// The details of our fake message
						CharSequence from = context.getText(R.string.alarm).toString() + "(" + temp_MEMO + ")";
						if (temp_MEMO == null || "".equals(temp_MEMO.trim())) {
							from = context.getText(R.string.alarm).toString();
						}
						
						CharSequence message = context.getText(R.string.sp_alarm_stop_NORMAL).toString();
						//[mo2sangbong.lee][1596] 2011.10.26 START
						PendingIntent contentIntent = PendingIntent.getActivity(context, aid, intent, 0);
						//[mo2sangbong.lee][1596] 2011.10.26 END
						Notification notif = new Notification(R.drawable.stat_notify_alarm, from, mTime );
						
						// Set the info for the views that show in the notification panel.
						notif.setLatestEventInfo(context, from, message, contentIntent);
						notif.deleteIntent = contentIntent;
						notif.flags |= Notification.FLAG_AUTO_CANCEL;
						
				        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
				        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
				        		&& CommonUtil.isPowerLEDSetInSettings(context.getContentResolver()) == 0){
				        	
				        	notif.flags |= Notification.DEFAULT_LIGHTS;
				        	
				        }else{
				        	
				        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
				        	notif.defaults |= Notification.DEFAULT_LIGHTS;
				        	
				        } //End Of if
//						notif.ledARGB = 0xFF00FF00;
//						notif.ledOnMS = 500;
//						notif.ledOffMS = 500;
						nm.notify(aid,  notif);
						
						/** 
						* not repeat 
						*/
						Alarms.noRepeatChecking(context, aid, true);
					} else {
						Log.d(TAG, " =============  SNOOZE =============  " );
						snooze = getSnoozeTime(context, aid);
						autoSnoozeGoAhead(context, aid, temp_MEMO, snooze, temp_TONE, temp_VIB, temp_PUZZLE);
					}
				} while(cc.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cc != null)
				cc.close();
		}
    }
    
    /**
     * snooze (Off / 5m / 10m/ 20m / 30m/ 60m)
     * @param id
     * @return
     */
    private int getSnoozeTime(Context context, int alarmId) {
    	int snoozeSet = 0 ;   
        
    	boolean isUseVolumeControl = CommonUtil.isUseVolumeControl();
    	
        ContentResolver resolver = context.getContentResolver(); 
        Cursor cc = null;
        try {
        	cc = resolver.query(  ALProvider.CONTENT_ALARMS_URI, isUseVolumeControl ? 
        			ALARM_NEED_COLUMNS_2 : ALARM_NEED_COLUMNS, "_id=" + alarmId, null, null );
            if (cc != null && cc.moveToFirst()) {//[hyunjung78.park] 2011.08.09 cursor null check
            	do {  
            		snoozeSet =	cc.getInt(ALARM_NEED_COLUMNS_IDX_ALARM_SNOOZE);
    				if (!"Off".equalsIgnoreCase(cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_TONE))) {
    					temp_TONE =	cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_TONE);
    				} else {
    					temp_TONE =	"Off";
    				}
    				temp_VIB = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_VIB);
    				temp_MEMO = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_MEMO); 
    				temp_PUZZLE = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_PUZZLE);
/* I3.0 Code [START] */
    				if(isUseVolumeControl)
    					temp_ALARMVOLUME = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_VOLUME);
/* I3.0 Code [END] */
            	} while(cc.moveToNext());
            }
        } catch ( Exception e ) {
        	e.printStackTrace();
        } finally {
        	if ( cc != null )
        		cc.close();
        }
        
    	return snoozeSet;
    }
    
    // when recording, auto snooze
    
    private void autoStop(Context context, int id, String memo, long rTime){
    	NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    	
		// notification
        ///////////// begin /////////////////////////////////////
        Intent aa = new Intent(context, ALReceiver.class);
        aa.setAction(Alarms.ALARM_STOP);
        aa.putExtra("id", id);     
        aa.putExtra("memo", memo);  
        PendingIntent broadcast =	PendingIntent.getBroadcast(context, id, aa, 0);
        CharSequence from = context.getText(R.string.alarm).toString() + "(" + memo +")";
    	if (memo == null || "".equals(memo.trim())) {
    	   	from =  context.getText(R.string.alarm).toString();
    	} 
    	
		CharSequence message = context.getText(R.string.sp_alarm_stop_NORMAL).toString();
		CharSequence message1 = context.getText(R.string.alarm).toString() + " " +  getCalendar(rTime, context) ;
		
		///////////////////////////////////////////////////////////////////////////////////////////////////////////
		Notification notif = new Notification(R.drawable.stat_notify_alarm, from, rTime );
        // Set the info for the views that show in the notification panel.
        notif.setLatestEventInfo(context, from, message, broadcast);
        notif.deleteIntent = broadcast;
        notif.flags |= Notification.FLAG_AUTO_CANCEL;
        
        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
        		&& CommonUtil.isPowerLEDSetInSettings(context.getContentResolver()) == 0){
        	
        	notif.flags |= Notification.DEFAULT_LIGHTS;
        	
        }else{
        	
        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
        	notif.defaults |= Notification.DEFAULT_LIGHTS;
        	
        } //End Of if
//        notif.ledARGB = 0xFF00FF00;
//        notif.ledOnMS = 500;
//        notif.ledOffMS = 500;
        nm.notify(id,  notif);     
        ///////////// end /////////////////////////////////////
        Toast.makeText(context, message1,  Toast.LENGTH_LONG).show();    
                
        /** 
    	* not repeat 
    	*/
        Alarms.noRepeatChecking(context, id, true);   
    }
    
    private void autoSnoozeGoAhead(Context context, int mID, String mMEMO, int mSNOOZE, String mTONE, String mVIB, String mPuzzle){
    	/*[START] 2012.04.03 suein1209.kim*/
//    	if ( mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE ) {
    	/*[END] 2012.04.03 suein1209.kim*/
    	if (CommonUtil.isCallStateIdle(mTelephonyManager, context) == false) {
    		NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
	    	nm.cancel(mID);
    	}
    	
    	ContentResolver resolver = context.getContentResolver();
        
    	int snooze_count = 0;
		Cursor cur = null;
		try {
			cur = resolver.query(ALProvider.CONTENT_CALCU_URI, new String[] { "_id" }, "aid=" + mID + "  and  aindex > 0" , null, null);
			if(cur != null)//[hyunjung78.park] 2011.08.09 cursor null check
			snooze_count = cur.getCount();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cur != null)
				cur.close();
		}
		
		int totalCount = 0;
		if ( snooze_count > 0 ) {
			resolver.delete(ALProvider.CONTENT_CALCU_URI, "aid=" + mID + "  and  aindex > 0",  null);
			totalCount = (snooze_count + 1);
		} else if (snooze_count == 0) { // last snooze check 
			totalCount = 5; // autosooze counting
		}
		
		final String[] alarmNeedColumns = { "daysofweek", "hour", "minutes" };
		int daysofweek = 0, hour = 0, minutes = 0;
        Cursor cc = null;
		try {
			cc = resolver.query(ALProvider.CONTENT_ALARMS_URI, alarmNeedColumns, "_id=" + mID, null, null );
	        
	        if (cc != null && cc.moveToFirst()) {//[hyunjung78.park] 2011.08.09 cursor null check
        		daysofweek	=  cc.getInt(0);
        		hour		=  cc.getInt(1);
        		minutes		=  cc.getInt(2);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cc != null)
				cc.close();
		}
        
        Calendar c3 = Calendar.getInstance();
        c3.set(Calendar.SECOND, 0);
        c3.set(Calendar.MILLISECOND, 0);
        long snooze_time = c3.getTimeInMillis();
        
        ContentValues values = null;    	         
        Date dd1 = null;
         
        //long nextTime = 0;
        Log.d(TAG, " == SnoozeRefreshing === START mTIME =======> " + snooze_time + "  /  snooze(min) interval => " + mSNOOZE );   
        for (int i = 1 ;  i <= totalCount; i++ )                            
        {                
        	long aa	= snooze_time + (1000 * 60 * i * mSNOOZE);
        	c3.setTimeInMillis( aa );
        	//if (i == 1) {
        	//	nextTime = aa;
        	//}
        	
        	dd1 = c3.getTime();   
            Log.d(TAG,  i + " th=>" + c3.getTimeInMillis() + " Time=>" + dd1.toString() );     
            Log.d(TAG,  "============================================================"  );
                                                     
            values = new ContentValues();
            values.put( "aid",   	mID);  
            values.put( "aindex",  	i ); 
            ////////////////////////////////////////////////
            values.put( "hour",  hour );        
            values.put( "minutes",  	minutes );
            values.put( "daysofweek",  	daysofweek ); 
            values.put( "enabled",  	1 );
            values.put( "time",  		c3.getTimeInMillis() );
            values.put( "status",  		"S" );
            if (i != totalCount) {
            	values.put( "stop", "" );
            }else {
            	values.put( "stop", "stop" );
            }  
            ////////////////////////////////////////////////                      
    		resolver.insert(ALProvider.CONTENT_CALCU_URI, values);       		
        }
		
        // seungchul.kang@lge.com  notification duplication
        ///////////////////////////////////////////////////////////////////////////////////////
    	// Notify the user that the alarm has been snoozed.
//        Intent cancelSnooze = new Intent(context, ALReceiver.class);
//        cancelSnooze.setAction(Alarms.CANCEL_SNOOZE);
//        cancelSnooze.putExtra("id", mID);
//                 
//        PendingIntent broadcast =	PendingIntent.getBroadcast(context, mID, cancelSnooze, 0);
//        // The details of our fake message
//        CharSequence from = null ;
//        if (mMEMO == null || "".equals(mMEMO.trim())) {
//        	from =  context.getText(R.string.sp_snooze_ment_NORMAL).toString();
//        
//        } else {
//        	from =  context.getText(R.string.sp_snooze_ment_NORMAL).toString() + "(" + mMEMO + ")" ;   
//        }
//        
//        CharSequence message = context.getText(R.string.alarm_ment1).toString() + " " + getCalendar(nextTime) ;
//        Notification notif = new Notification(R.drawable.stat_notify_alarm, from, 0);
//        notif.setLatestEventInfo(context, from, message,  broadcast);
//        notif.deleteIntent = broadcast;
//        notif.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONGOING_EVENT;
//        nm.notify(mID, notif);        
        /////////////////////////////////////////////////////////////////
	}
	// [suhyun99.kim][1395] 2011.10.27. START
//	private void sdChangeProc(Context context) {
//		Log.d(TAG, "=====sdChangeProc====");
//		
//		if (!Environment.isExternalStorageRemovable()){
//			Log.d(TAG, "=====sdChangeProc==(Environment.isExternalStorageRemovable==");
//			return;
//		}
//		
//		int volumeID = android.os.FileUtils.getFatVolumeId(CommonUtil.getExternalStorageDirectory());
//        SharedPreferences mPrefs = context.getSharedPreferences("EXTERNAL_SDCARD_STATE", 0);
//        int oldVolumeID = mPrefs.getInt("sdcardid", 0);
//        Log.e(TAG, "=====sdChangeProc__sdcard changed====" + "oldVolumeID = " + oldVolumeID + "    volumeID = " + volumeID);
//	    if(oldVolumeID != volumeID ) {
//			mPrefs.edit().putInt("sdcardid", volumeID).commit();
//
//			Cursor cur = null;
//			try {
//				cur = context.getContentResolver().query(ALProvider.CONTENT_ALARMS_URI, PROJECTION, null, null, null);
//				String id = "";
//				String uri = "";
//				String defaulttone = "content://media/internal/audio/media/1";
//				if(cur != null){
//					cur.moveToFirst();
//	        	            	do {
//	        	            		id = cur.getString(0) ;
//	        	            		uri = cur.getString(1);
//	        	            		if (uri.indexOf("content://media/external") >= 0) {
//	        	            			ContentValues values = new ContentValues();
//										values.put("tone", defaulttone );
//	        	            			context.getContentResolver().update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + id, null);
//	        	            		}
//	        	            	} while(cur.moveToNext());
//	    			Alarms.setNextAlert(context);
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			} finally {
//				if (cur != null) 
//				cur.close();
//			}
//		}
//    }
	
	// [suhyun99.kim][1395] 2011.10.27. END
}

